var gulp = require('gulp');
var uglifyjs = require("gulp-uglify");
var uglifycss = require("gulp-minify-css");
var uglifyhtml = require("gulp-minify-html");
var uglifyimages = require("gulp-imagemin");
var jshint = require("gulp-jshint");
var concatjs = require("gulp-concat");
var renamejs = require("gulp-rename");
var lesscs = require("gulp-less");
var LiveReload = require('gulp-livereload');


//JS文件与压缩任务
gulp.task("JSuglify",function(){
	gulp.src(["src/js/apps/index.js","src/js/apps/demo.js"])
		.pipe(uglifyjs())
		.pipe(gulp.dest("dist/js/apps"))

});

//CSS文件压缩
gulp.task("CSSuglify",function(){
	gulp.src("src/css/*.css")
		.pipe(uglifycss())
		.pipe(gulp.dest("dist/css"))
})

//HTML文件压缩
gulp.task("HTMLuglify",function(){
	gulp.src("src/index.html")
		.pipe(uglifyhtml())
		.pipe(gulp.dest("dist"))
});


// http://blog.csdn.net/u013063153/article/details/52628506
// 压缩图片
gulp.task("imageuglify", function() {
	gulp.src("src/images/*.{png,jpg,gif,ico,jpeg}")
		.pipe(uglifyimages({
			progressive: true, // 压缩无损图片
			multipass: true // 多次优化svg直到完全优化
		}))
		.pipe(gulp.dest("dist/images"))
});

//编码检查
gulp.task("Jshint",function(){
	gulp.src("src/js/apps/*.js")
	.pipe(jshint())
	.pipe(jshint.reporter());
});

//js合并、压缩、重命名
gulp.task("final",function(){
	gulp.src("src/js/apps/*.js")
		.pipe(concatjs("app.js"))//合并后需要命名文件
		.pipe(uglifyjs())
		.pipe(renamejs({
			suffix:".min"
		}))//重命名后需要改名字
		.pipe(gulp.dest("dist/js/apps/final"))
});

//css合并、压缩、重命名
gulp.task("final",function(){
	gulp.src("src/js/apps/*.js")
		.pipe(concatjs("app.js"))//合并后需要命名文件
		.pipe(uglifyjs())
		.pipe(renamejs({
			suffix:".min"
		}))//重命名后需要改名字
		.pipe(gulp.dest("dist/js/apps/final"))
});



//监听
gulp.task('watch',function(){
	gulp.watch("src/js/apps/*.js",function(){
		gulp.run('final')
	})
});


//编译less文件
gulp.task('lessCSS',function(){
	gulp.src('src/css/demo.less')
		.pipe(lesscs())
		.pipe(gulp.dest('dist/css'))
});


//****重点：热更新
gulp.task('hot',function(){
	LiveReload.listen();
	gulp.watch('src/index.html',function(event){
		LiveReload.changed(event.path);
	});
});


gulp.task('default', function() {
  // 将你的默认的任务代码放在这
  // console.log(123);
  gulp.start(["JSuglify"]);
});